<template>
  <div class="order-list">
    <h1 class="page-title">订单分配页面</h1>
    <div class="table-container">
      <!-- 查询表单 -->
      <el-card class="search-card">
        <el-form :model="queryForm" inline @submit.prevent="fetchWorkOrderList">
          <el-form-item label="工单ID">
            <el-input 
              v-model="queryForm.id" 
              placeholder="请输入工单ID" 
              clearable 
              @keyup.enter="fetchWorkOrderList"
              @input="debounceQuery"
            ></el-input>
          </el-form-item>
          <el-form-item label="工单标题">
            <el-input 
              v-model="queryForm.title" 
              placeholder="请输入工单标题" 
              clearable 
              @keyup.enter="fetchWorkOrderList"
              @input="debounceQuery"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系人">
            <el-input 
              v-model="queryForm.name" 
              placeholder="请输入联系人" 
              clearable 
              @keyup.enter="fetchWorkOrderList"
              @input="debounceQuery"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchWorkOrderList" :loading="loading">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      
      <!-- 添加刷新按钮 -->
      <div style="margin: 15px 0;">
        <el-button type="primary" @click="fetchWorkOrderList" :loading="loading">
          {{ loading ? '加载中...' : '刷新' }}
        </el-button>
        <el-button @click="fetchUsers">刷新用户</el-button>
      </div>
      
      <el-table :data="workOrderList" style="width: 100%" border v-loading="loading">
        <el-table-column prop="id" label="工单ID" width="120" />
        <el-table-column prop="title" label="工单标题" width="180" />
        <el-table-column prop="name" label="联系人" width="100" />
        <el-table-column prop="type" label="工单类型" width="100">
          <template #default="scope">
            <span v-if="scope.row.type === 0">普通</span>
            <span v-else-if="scope.row.type === 1">紧急</span>
            <span v-else>未知类型</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button size="small" @click="handleViewDetail(scope.row)">详情</el-button>
            <el-button size="small" @click="showEditForm(scope.row)">编辑</el-button>
            <el-button size="small" type="primary" @click="assignOrder(scope.row)">分配</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分配对话框 -->
    <el-dialog title="分配工单" v-model="assignDialogVisible" width="600px">
      <el-form :model="assignForm" label-width="100px">
        <el-form-item label="工单ID">
          <el-input v-model="assignForm.orderId" disabled></el-input>
        </el-form-item>
        <el-form-item label="工单标题">
          <el-input v-model="assignForm.orderTitle" disabled></el-input>
        </el-form-item>
        <el-form-item label="调度员">
          <el-select v-model="assignForm.dispatcherId" placeholder="请选择调度员" disabled>
            <el-option
              v-for="dispatcher in dispatchers"
              :key="dispatcher.id || dispatcher.name"
              :label="dispatcher.name || '未知调度员'"
              :value="dispatcher.id || 0">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接单员">
          <el-select v-model="assignForm.employeeId" placeholder="请选择接单员">
            <el-option
              v-for="employee in employees"
              :key="employee.id || employee.name"
              :label="employee.name || '未知员工'"
              :value="employee.id || 0">
            </el-option>
          </el-select>
          <div style="margin-top: 10px; font-size: 12px; color: #999;">
            共 {{ employees.length }} 名员工
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAssign">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getWorkOrderListAPI, assignOrderAPI, deleteOrderAPI, updateOrderAPI } from '@/apis/order'
import { getUserListAPI, getUserInfoAPI, getUserRolesAPI } from '@/apis/sys'
import { useUserStore } from '@/stores/user'

export default {
  name: 'OrderDistribution',
  data() {
    return {
      workOrderList: [],
      loading: false,
      // 分配对话框可见性
      assignDialogVisible: false,
      // 编辑表单可见性
      editFormVisible: false,
      // 分配表单数据
      assignForm: {
        orderId: '',
        orderTitle: '',
        dispatcherId: '',
        employeeId: ''
      },
      // 调度员数据
      dispatchers: [],
      // 接单员数据
      employees: [],
      // 编辑表单数据
      editForm: {
        id: undefined,
        title: '',
        des: '',
        name: '',
        phone: '',
        address: '',
        payStatus: 0,
        status: 0,
        type: 0
      },
      // 添加查询表单数据
      queryForm: {
        id: '',
        title: '',
        name: '',
        phone: '',
        status: '',
        type: ''
      },
      // 添加防抖定时器
      queryTimer: null,
      // 表单验证规则
      rules: {
        title: [
          { required: true, message: '请输入工单标题', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.fetchWorkOrderList()
    this.fetchUsers()
  },
  methods: {
    async fetchWorkOrderList() {
      this.loading = true
      try {
        const res = await getWorkOrderListAPI()
        if (res.code === 0) {
          // 只显示状态为0的工单（未处理）
          let filteredData = res.data.filter(item => item.status === 0)
          
          // 根据查询条件过滤数据
          if (this.queryForm.id) {
            filteredData = filteredData.filter(item => 
              item.id && item.id.toString().includes(this.queryForm.id)
            )
          }
          
          if (this.queryForm.title) {
            filteredData = filteredData.filter(item => 
              item.title && item.title.includes(this.queryForm.title)
            )
          }
          
          if (this.queryForm.name) {
            filteredData = filteredData.filter(item => 
              item.name && item.name.includes(this.queryForm.name)
            )
          }
          
          // 显示过滤后的数据
          this.workOrderList = filteredData.map(item => {
            return {
              id: item.id,
              title: item.title || '无标题',
              des: item.des || '无描述',
              name: item.name || '无联系人',
              phone: item.phone || '无联系电话',
              address: item.address || '无地址',
              payStatus: item.payStatus,
              status: item.status,
              pic: item.pic || '',
              productId: item.productId || '',
              dispatcherId: item.dispatcherId || '',
              employeeId: item.employeeId || '',
              type: item.type,
              createTime: item.createTime || new Date().toISOString(),
              updateTime: item.updateTime || new Date().toISOString()
            }
          })
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '获取工单列表失败'
          })
        }
      } catch (error) {
        this.$message({
          type: 'error',
          message: '获取工单列表失败: ' + (error.msg || error.message || '未知错误')
        })
        console.error('获取工单列表失败:', error)
      } finally {
        this.loading = false
      }
    },
    // 添加防抖查询功能
    debounceQuery() {
      // 清除之前的定时器
      if (this.queryTimer) {
        clearTimeout(this.queryTimer)
      }
      
      // 设置新的定时器
      this.queryTimer = setTimeout(() => {
        this.fetchWorkOrderList()
      }, 300)
    },
    // 添加重置查询功能
    resetQuery() {
      this.queryForm = {
        id: '',
        title: '',
        name: ''
      }
      this.fetchWorkOrderList()
    },
    
    // 获取用户列表
    async fetchUsers() {
      try {
        // 获取当前登录用户信息
        const userStore = useUserStore()
        console.log('用户存储信息:', userStore.userInfo)
        // 从正确的字段获取用户ID
        const currentUserId = userStore.userInfo?.user?.id
        console.log('当前登录用户ID:', currentUserId)
        
        if (!currentUserId) {
          this.$message({
            type: 'error',
            message: '未获取到当前用户信息，请重新登录'
          })
          return
        }
        
        // 获取当前登录用户详细信息
        const currentUserRes = await getUserInfoAPI(currentUserId)
        console.log('当前用户详细信息:', currentUserRes)
        
        if (currentUserRes.code !== 0) {
          this.$message({
            type: 'error',
            message: '获取当前用户详细信息失败: ' + (currentUserRes.msg || '未知错误')
          })
          return
        }
        
        const currentUserInfo = currentUserRes.data
        console.log('当前用户完整信息:', currentUserInfo)
        
        // 设置当前调度员
        this.dispatchers = [{
          id: currentUserInfo.user?.id || currentUserInfo.userInfoVO?.id || currentUserInfo.user?.userId || 0,
          name: currentUserInfo.user?.userName || currentUserInfo.userInfoVO?.userName || '未知调度员',
          role: 'dispatcher'
        }]
        
        // 设置调度员工单默认值
        this.assignForm.dispatcherId = currentUserInfo.user?.id || currentUserInfo.userInfoVO?.id || currentUserInfo.user?.userId || 0
        
        // 获取所有用户列表并筛选出员工
        await this.fetchEmployees()
      } catch (error) {
        this.$message({
          type: 'error',
          message: '获取用户信息失败: ' + (error.msg || error.message || '未知错误')
        })
        console.error('获取用户信息失败:', error)
      }
    },
    
    // 获取接单员列表（只显示具有"员工"角色的用户）
    async fetchEmployees() {
      try {
        const res = await getUserListAPI()
        console.log('获取用户列表:', res)
        if (res.code === 0) {
          // 从用户列表中获取所有用户
          const users = res.data || []
          console.log('所有用户:', users)
          
          // 并行获取所有用户的角色信息并筛选出员工
          const userRolePromises = users.map(user => 
            getUserRolesAPI(user.id).then(roleRes => ({ user, roleRes }))
          )
          
          const userRoles = await Promise.all(userRolePromises)
          console.log('所有用户角色信息:', userRoles)
          
          // 筛选角色为"员工"的用户作为接单员
          this.employees = []
          for (const { user, roleRes } of userRoles) {
            try {
              // 根据后端返回的数据格式进行处理
              if (roleRes.code === 0) {
                // 处理不同格式的角色数据
                let isEmployee = false
                
                if (Array.isArray(roleRes.data)) {
                  // 数组格式，检查是否有名称为"员工"的角色
                  isEmployee = roleRes.data.some(role => 
                    (role.roleName === '接单员') || (role.name === '接单员')
                  )
                } else if (typeof roleRes.data === 'object' && roleRes.data !== null) {
                  // 对象格式
                  if ((roleRes.data.roleName === '接单员') || (roleRes.data.name === '接单员')) {
                    isEmployee = true
                  }
                } else if (typeof roleRes.data === 'string') {
                  // 字符串格式，直接比较是否为"员工"
                  if (roleRes.data === '接单员') {
                    isEmployee = true
                  }
                }
                
                // 如果用户是员工，则添加到员工列表
                if (isEmployee) {
                  this.employees.push({
                    id: user.id || 0,
                    name: user.userName || '未知员工',
                    role: 'employee'
                  })
                }
              }
            } catch (error) {
              console.error(`处理用户${user.id}角色信息时发生错误:`, error)
            }
          }
          
          console.log('筛选后的员工列表:', this.employees)
          
          // 如果没有找到员工，显示提示信息
          if (this.employees.length === 0) {
            this.$message({
              type: 'warning',
              message: '未找到角色为员工的用户'
            })
          }
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '获取用户列表失败'
          })
        }
      } catch (error) {
        this.$message({
          type: 'error',
          message: '获取员工列表失败: ' + (error.msg || error.message || '未知错误')
        })
        console.error('获取员工列表失败:', error)
      }
    },
    
    // 查看详情
    handleViewDetail(row) {
      this.$router.push({
        name: 'OrderDetail',
        query: {
          id: row.id
        }
      })
    },
    
    showEditForm(row) {
      this.editForm = { ...row }
      this.editFormVisible = true
    },
    
    // 处理编辑表单提交
    handleEdit() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          try {
            const res = await updateOrderAPI(this.editForm)
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: '更新工单成功!'
              })
              this.editFormVisible = false
              // 重新获取列表数据
              this.fetchWorkOrderList()
            } else {
              this.$message({
                type: 'error',
                message: res.msg || '更新工单失败'
              })
            }
          } catch (error) {
            // 检查是否是Promise.reject返回的业务异常
            if (error && error.msg) {
              this.$message({
                type: 'error',
                message: '更新工单失败: ' + error.msg
              })
            } else {
              this.$message({
                type: 'error',
                message: '更新工单失败: ' + (error.message || '未知错误')
              })
            }
            console.error('更新工单失败:', error)
          }
        } else {
          console.log('表单验证失败!')
          return false
        }
      })
    },
    
    // 显示分配对话框
    assignOrder(row) {
      // 确保用户列表已加载
      if (this.dispatchers.length === 0 || this.employees.length === 0) {
        this.fetchUsers()
      }
      
      this.assignForm = {
        orderId: row.id,
        orderTitle: row.title,
        dispatcherId: this.assignForm.dispatcherId, // 使用当前调度员
        employeeId: row.employeeId || ''
      }
      
      this.assignDialogVisible = true
    },
    
    // 提交分配
    async submitAssign() {
      if (!this.assignForm.dispatcherId || !this.assignForm.employeeId) {
        this.$message({
          type: 'warning',
          message: '请选择调度员和接单员'
        })
        return
      }

      try {
        const params = {
          id: this.assignForm.orderId,
          dispatcherId: this.assignForm.dispatcherId,
          employeeId: this.assignForm.employeeId
        }

        const res = await assignOrderAPI(params)
        if (res.code === 0) {
          this.$message({
            type: 'success',
            message: '分配成功!'
          })
          this.assignDialogVisible = false
          // 重新获取列表数据
          this.fetchWorkOrderList()
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '分配失败'
          })
        }
      } catch (error) {
        this.$message({
          type: 'error',
          message: '分配失败: ' + (error.msg || error.message || '未知错误')
        })
        console.error('分配失败:', error)
      }
    },
    // 添加删除功能
    handleDelete(row) {
      this.$confirm(`确定要删除工单 "${row.title}" 吗？`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await deleteOrderAPI(row.id)
          if (res.code === 0) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 重新获取列表数据
            this.fetchWorkOrderList()
          } else {
            this.$message({
              type: 'error',
              message: res.msg || '删除失败'
            })
          }
        } catch (error) {
          this.$message({
            type: 'error',
            message: '删除失败: ' + (error.msg || error.message || '未知错误')
          })
          console.error('删除失败:', error)
        }
      }).catch(() => {
        // 用户取消删除
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    getTypeText(type) {
      switch (type) {
        case 0: // NORMAL
          return '普通'
        case 1: // URGENT
          return '紧急'
        default:
          return '未知类型'
      }
    }
  }
}
</script>

<style scoped>
.order-list {
  padding: 20px;
  background-color: #f5f5f5;
  text-align: center;
}

.page-title {
  font-size: 2.2rem;
  color: #2c3e50;
  margin: 20px 0;
  text-align: center;
  font-weight: bold;
}

.table-container {
  margin-top: 20px;
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  text-align: left;
}

.search-card {
  margin-bottom: 15px;
  border-radius: 4px;
}

.search-card :deep(.el-card__body) {
  padding: 15px;
}

.dialog-footer {
  text-align: right;
}

.employee-table {
  margin-top: 20px;
}

@media (max-width: 768px) {
  .page-title {
    font-size: 1.8rem;
  }
}
</style>